
Function.prototype.bind = function() {
    // http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions:arguments
    var _$A = function(a) {
        return Array.prototype.slice.call(a);
    }
    if (arguments.length < 2 && (typeof arguments[0] == "undefined")) return this;
    var __method = this,
        args = _$A(arguments),
        object = args.shift();
    return function() {
        return __method.apply(object, args.concat(_$A(arguments)));
    }
};

jQuery.fn.extend({
    getClasses: function() {
        var classes = new Array();

        jQuery(this).each(function() {
            classes = classes.concat(jQuery(this).attr("class").split(" "));
        });

        return classes;
    },

    eachClass: function(callback) {
        jQuery(this).each(function() {
            var _class = jQuery(this).attr("class");
            if (typeof _class != "undefined") jQuery.each(_class.split(" "), callback);
        });

        return this;
    },

    setTextField: function(e, maxLength) {
        jQuery(this).focus(function() {
            jQuery(this).removeClass("default").addClass("focus").unbind("focus");
        }).keyup(function() {
            if (!e || !maxLength) return;

            var bytes = bugs.utils.byteSize($(this).val());

            var html = "(" + bytes + " / " + maxLength + ")";
            if (bytes > maxLength) html = "<em>글자수가 초과되었습니다. 다시 입력해 주세요.</em>" + html;
            e.html(html);
        });

        return this;
    },

    openWindow: function(callback) {
        jQuery(this).click(function() {
            var href = jQuery(this).attr("href");
            window.open(href);

            if (typeof(callback) == "function") callback();

            return false;
        });
        return this;
    },

    popupWindow: function(option, callback) {
        var opt = bugs.overed({
            method: "GET",
            objFrom: null,
            url: null,
            name: null,
            width: 500,
            height: 500,
            top: 0,
            left: 0,
            center: 0,
            location: 0,
            menubar: 0,
            toolbar: 0,
            status: 0,
            scrollbars: 0,
            resizable: 0
        }, option || {});

        var top, left;
        if (opt.center) {
            if ($.browser.msie) {
                top = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120) / 2) - (opt.height / 2)));
                left = window.screenLeft + ((((document.body.offsetWidth + 20) / 2) - (opt.width / 2)));
            } else {
                top = window.screenY + (((window.outerHeight / 2) - (opt.height / 2)));
                left = window.screenX + (((window.outerWidth / 2) - (opt.width / 2)));
            }
        } else {
            top = opt.top;
            left = opt.left;
        }

        var features = "width=" + opt.width + ",height=" + opt.height + ",location=" + opt.location + ",menuBar=" + opt.menubar + ",toolbar=" + opt.toolbar + ",status=" + opt.status + ",scrollbars=" + opt.scrollbars + ",resizable=" + opt.resizable;

        var objPopup = null;
        if (opt.method.toUpperCase() == "POST") {
            objPopup = window.open("", opt.name, features + ",top=" + top + ",left=" + left);

            $(opt.objFrom).attr("method", "post");
            $(opt.objFrom).attr("target", opt.name);
            $(opt.objFrom).attr("action", opt.url);
            $(opt.objFrom).submit();
        } else {
            objPopup = window.open(opt.url, opt.name, features + ",top=" + top + ",left=" + left);
        }

        if (objPopup == null) {
            alert("차단된 팝업창을 허용 후에 이용하시 수 있습니다.");
        } else {
            objPopup.focus();
        }

        return objPopup;
    },

    nextInput: function(nextElem, maxLength) {
        jQuery(this).keyup(function() {
            if (!nextElem || !maxLength) return;
            if ($(this).val().length >= maxLength) {
                jQuery(this).removeClass("focus").addClass("default");
                $(nextElem).focus();
            }
        });
        return this;
    }
});



bugs = {
    create: function() {
        return function() {
            this.initialize.apply(this, arguments);
        }
    },
    overed: function(destination, source) {
        for (var property in source) {
            destination[property] = source[property];
        }
        return destination;
    },
    extend: function(ext, sup) {
        var ext_prototype = ext.prototype;
        var sup_prototype = sup.prototype;
        for (var property in sup_prototype) {
            if (!ext_prototype[property]) ext_prototype[property] = sup_prototype[property];
        }
    },
    clone: function(obj) {
        var newObj = {};
        for (var property in obj) newObj[property] = obj[property];
        return newObj;
    },
    log: {
        LEVEL: 2,
        levels: {
            DEBUG: 0,
            INFO: 1,
            ERROR: 2
        },
        setLogLevel: function(lv) {
            if (lv == "DEBUG") bugs.log.LEVEL = bugs.log.levels.DEBUG;
            else if (lv == "INFO") bugs.log.LEVEL = bugs.log.levels.DEBUG;
            else if (lv == "ERROR") bugs.log.LEVEL = bugs.log.levels.DEBUG;
        },
        log: function(s) {
            try {
                if (typeof(console) != "undefined") console.log(s);
                //else alert(bugs.object.toString(s));
            } catch (e) {}
        },
        debug: function(s) {
            if (bugs.log.LEVEL <= bugs.log.levels.DEBUG) bugs.log.log(s);;
        },
        info: function(s) {
            if (bugs.log.LEVEL <= bugs.log.levels.INFO) bugs.log.log(s);;
        },
        error: function(s) {
            if (bugs.log.LEVEL <= bugs.log.levels.ERROR) bugs.log.log(s);;
        },
        dump: function(s) {
            var newLog = "";
            switch ((typeof s).toLowerCase()) {
                case "object":
                    $.each(s, function(key, value) {
                        newLog += "[" + (typeof value) + "] " + key + " : " + value + "\n";
                    });
                    break;

                case "string":
                default:
                    newLog += "[" + (typeof s) + "] " + s;
            }
            bugs.log.log(newLog);
        }
    },
    date: {
        yyyyMMdd: function(d) {
            if (!d) d = new Date();
            return d.yyyyMMdd();
        }
    },
    math: {
        abs: function(x) {
            return Math.abs(x);
        },
        random: function(n) {
            if (typeof(n) == "undefined") return Math.random();
            else return bugs.math.floor(Math.random() * n, 0);
        },
        round: function(n, index) {
            return bugs.math._get(Math.round, n, index);
        },
        ceil: function(n, index) {
            return bugs.math._get(Math.ceil, n, index);
        },
        floor: function(n, index) {
            return bugs.math._get(Math.floor, n, index);
        },
        _get: function(type, n, index) {
            if (typeof(index) == "undefined" || index == null) {
                index = 0;
            }
            //if(index==0) return eval("Math."+type+"(n)");
            if (index == 0) return type(n);
            else {
                var p = Math.pow(10, index);
                //				return eval("Math."+type+"(n * p) / p");
                return type(n * p) / p;
            }
        }
    },
    cookie: {
        set: function(name, value) {
            var argc = arguments.length;
            var argv = arguments;
            var expires = (argc > 2) ? argv[2] : null;
            var path = (argc > 3) ? argv[3] : null;
            var domain = (argc > 4) ? argv[4] : null;
            var secure = (argc > 5) ? argv[5] : false;
            var encode = (argc > 6) ? argv[6] : true;

            var expireDate = new Date();
            expireDate.setTime(expires);

            document.cookie = name + "=" + (encode ? escape(value) : value) + ((expires == null) ? "" : ("; expires =" + expireDate.toGMTString())) + ((path == null) ? "" : ("; path =" + path)) + ((domain == null) ? "" : ("; domain =" + domain)) + ((secure == true) ? "; secure" : "");
        },
        get: function(name) {
            var dcookie = document.cookie;
            var cname = name + "=";
            var clen = dcookie.length;
            var cbegin = 0;
            while (cbegin < clen) {
                var vbegin = cbegin + cname.length;
                if (dcookie.substring(cbegin, vbegin) == cname) {
                    var vend = dcookie.indexOf(";", vbegin);
                    if (vend == -1) vend = clen;
                    return unescape(dcookie.substring(vbegin, vend));
                }
                cbegin = dcookie.indexOf(" ", cbegin) + 1;
                if (cbegin == 0) break;
            }
            return "";
        },
        del: function(name) {
            var expTime = new Date();
            expTime.setTime(expTime.getTime() - 1);

            var cookieVal = bugs.cookie.get(name);
            if (cookieVal != null) {
                bugs.cookie.set(name, cookieVal, expTime);
            }
        }
    },
    visible: function(e) {
        var _is_display = false;
        if (e) {
            return (e.get(0).style.display != "none");
        } else return false;
        /*
		if(e) e.each(function() {if(this.style.display != "none") _is_display = true; });
		return _is_display;
		*/
    },
    focusNblur: function(selector, focusClass, blurClass) {
        if (typeof focusClass == "undefined") focusClass = "focus";
        if (typeof blurClass == "undefined") blurClass = "default";
        $(selector).focus(function(e) {
            var ee = $(e.target);
            ee.removeClass(blurClass);
            ee.addClass(focusClass);
        }).blur(function(e) {
            var ee = $(e.target);
            ee.removeClass(focusClass);
            ee.addClass(blurClass);
        });
    },
    object: {
        toString: function(obj) {
            var str = "";
            if (typeof obj == "string") return obj;
            else {
                for (var property in obj) {
                    str += property + ":" + "{" + bugs.object.toString(obj[property]) + "}";
                }
                return str;
            }
        },
        empty: function(obj) {
            if (typeof obj == "undefine" || obj == null) return true;
            if (typeof obj == "string") return bugs.valid.empty(obj);
            if (typeof obj == "object") {
                var _ret = true;
                for (var property in obj) {
                    _ret = false;
                    break;
                }
                return _ret;
            }
        }
    },
    utils: {
        stripTag: function(s) {
            s = s.replace(/&(lt|gt);/g, function(strMatch, p1) {
                return (p1 == "lt") ? "<" : ">";
            });
            return s.replace(/<\/?[^>]+(>|$)/g, "");
        },
        toTag: function(s) {
            s = s.replace(/&(lt|gt);/g, function(strMatch, p1) {
                return (p1 == "lt") ? "<" : ">";
            });
            return s;
        },
        cutstring: function(s, length, postfix) {
            if (!s) return "";
            if (!postfix) postfix = "";
            if (s.length <= length) return s;
            //			if(bugs.utils.byteSize(s) <= length) return s;
            else return s.substring(0, length) + postfix;
        },
        cutstring1: function(s, length) {
            return bugs.utils.cutstring(s, length, "...");
        },

        cutstring2: function(s, length) {
            if (s.length <= length) {
                return s;
            } else {
                return bugs.utils.trim(s.substring(0, length)) + "...";
            }
        },

        trim: function(str) {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        },
        replaceAll: function(str, srchStr, toStr) {
            while (str.indexOf(srchStr) != -1)
            str = str.replace(srchStr, toStr);

            return str;
        },
        byteSize: function(str, twoByteWeight) {
            if (typeof twoByteWeight == "undefined") twoByteWeight = 2;
            if (!str || typeof str != 'string') return 0;
            var cnt = 0;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) > 127) cnt += twoByteWeight;
                else cnt++;
            }

            return Math.ceil(cnt);
        },
        strlengthByByte: function(str, size, twoByteWeight) {
            if (typeof twoByteWeight == "undefined") twoByteWeight = 2;
            if (!str || typeof str != 'string') return 0;
            var cnt = 0,
                len = 0;

            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) > 127) cnt += twoByteWeight;
                else cnt++;
                if (cnt > size) return len;
                len++;

            }
            return len;
        },
        strlen: function(str) {
            var len = 0;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) > 128) len += 2;
                else len++;
            }
            return len;
        },
        numToStr: function(num) {
            if (num.length < 4) return num;

            while (num.indexOf(",") >= 0) {
                num = num.replace(",", "");
            }

            return num;
        },
        strToNum: function(str) {
            var num = "";
            var getString = "" + str;

            while (getString.length > 3) {
                num = "," + getString.substring(getString.length - 3, getString.length) + num;
                getString = getString.substring(0, getString.length - 3);
            }

            if (getString != "") num = "" + getString + num;

            return num;
        },
        cutbytestring: function(s, size, postfix, twoByteWeight) {
            if (!s) return "";
            if (!postfix) postfix = "";
            if (bugs.utils.byteSize(s) <= size) return s;
            else return s.substring(0, bugs.utils.strlengthByByte(s, size, twoByteWeight)) + postfix;
        },
        cutbytestring1: function(s, size, twoByteWeight) {
            return bugs.utils.cutbytestring(s, size, "...", twoByteWeight);
        },
        cut: function(str, size, postfix) {
            if (typeof(postfix) == 'undefined') postfix = '...';

            var bytes = bugs.utils.byteSize(str);
            if (bytes < size) return str;

            var cnt = 0,
                len = 0,
                t = -1;

            for (var i = 0; i < str.length; i++) {
                cnt += (str.charCodeAt(i) > 127) ? 2 : 1;

                if (t < 0 && (cnt + postfix.length > size)) t = len;

                if (cnt > size) break;
                len++;
            }

            if (cnt <= size) return str.substring(0, len);
            else return str.substring(0, t) + postfix;
        },
        cutline: function(str, size, line, postfix) {
            if (typeof(postfix) == 'undefined') postfix = '...';

            var cnt = 0,
                ln = 0,
                start = 0,
                end = 0;
            var result = '';

            for (var i = 0; i < str.length; i++) {
                cnt += (str.charCodeAt(i) > 127) ? 2 : 1;
                if (cnt > size) {
                    var tmp = str.substring(start, end);
                    ln++;

                    if (ln < line) result += tmp + "\n";
                    else {
                        if (i <= str.length - 1) tmp = bugs.utils.cut(tmp + postfix, size, postfix);

                        result += tmp;
                        break;
                    }

                    start = end++;
                    cnt = (str.charCodeAt(i) > 127) ? 2 : 1;
                } else end++;
            }

            if (ln < line && end > start) result += str.substring(start, end);

            return result;
        },
        countLine: function(str) {
            var line = 1;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) == 10) line++;
            }

            return line;
        },
        addCommas: function(nStr) {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        },
        // img out over
        imgOver: function(obj) {
            obj.src = obj.src.replace("Off.gif", "Over.gif");
        },
        imgOut: function(obj) {
            obj.src = obj.src.replace("Over.gif", "Off.gif");
        },

        imgOver2: function(obj) {
            obj.attr("src", obj.attr("src").replace("Off.gif", "Over.gif"));
        },

        imgOut2: function(obj) {
            obj.attr("src", obj.attr("src").replace("Over.gif", "Off.gif"));
        },

        /*
		imgError : function(obj, defaultSize) {
			if(!obj) return;
			
			// defaultSize가 argument에 있다면 소스 이미지가 썸네일이 아닌 오리지날 이미지로 
			// 해당 이미지가 없으면 바로 default 이미지를 보여줌. (썸네일 서버 부하 줄임)
			if(defaultSize) {
				obj.onerror = null;
				obj.src = bugs.url.defaultThumbnail(obj.src, defaultSize);
				//obj.src = g_urlThumbnail + "/requestDefaultImage?url=" + encodeURIComponent(obj.src);
			}
			else {
				obj.onerror = function() {
					obj.onerror = null;
					obj.src = bugs.url.defaultThumbnail(obj.src);
				};
				obj.src = g_urlThumbnail + "/request?url=" + encodeURIComponent(obj.src);
			}
		},
		setImgError : function(selector) {
			return $(selector).one("error", function() {
				$(this).one("error", function() {
					$(this).attr("src", bugs.url.defaultThumbnail($(this).attr("src")));
				});
				
				$(this).attr("src", g_urlThumbnail + "/request?url=" + encodeURIComponent($(this).attr("src")));
			});
		},
		*/
        imgError: function(obj, defaultSize) {
            if (!obj) return;

            // defaultSize가 argument에 있다면 소스 이미지가 썸네일이 아닌 오리지날 이미지로 
            // 해당 이미지가 없으면 바로 default 이미지를 보여줌. (썸네일 서버 부하 줄임)
            if (defaultSize) {
                obj.onerror = null;
                obj.src = bugs.url.defaultThumbnail(obj.src, defaultSize);
            } else {
                obj.onerror = null;
                obj.src = bugs.url.defaultThumbnail(obj.src);
            }
        },
        setImgError: function(selector) {
            return $(selector).one("error", function() {
                $(this).attr("src", bugs.url.defaultThumbnail($(this).attr("src")));
            });
        },

        bannerError: function(obj) {
            if (!obj) return;

            obj.onerror = null;
            obj.src = "http://file.bugsm.co.kr/bugs/images/common/noalbumD.gif";
        },
        setBannerError: function(selector) {
            return $(selector).one("error", function() {
                $(this).attr("src", "http://file.bugsm.co.kr/bugs/images/common/noalbumD.gif");
            });
        },
        moreView: function(anchor, obj, height) {
            if (typeof obj == "undefined") return;
            if (typeof obj == "string") obj = $(obj);
            if (typeof height == "undefined") height = 80;
            anchor = $(anchor);
            if (obj.css("overflow") == "hidden") {
                obj.css({
                    "height": null,
                    "overflow": "visible"
                });
                anchor.parent().addClass("close");
                anchor.html(anchor.html().replace("더보기", "닫기"));
            } else {
                bugs.log.log(obj.find("img"));
                obj.find("img").hide();

                obj.css({
                    "height": height,
                    "overflow": "hidden"
                });
                anchor.parent().removeClass("close");
                anchor.html(anchor.html().replace("닫기", "더보기"));
            }

        },
        toggleMoreView: function(anchor) {
            anchor = $(anchor);
            if (anchor.text() == "더보기") {
                anchor.parent().addClass("close");
                anchor.html(anchor.html().replace("더보기", "닫기"));
            } else {
                anchor.parent().removeClass("close");
                anchor.html(anchor.html().replace("닫기", "더보기"));
            }
        },
        parentOpenClose: function(obj, headSelector, listSelector) {
            var oo = $(headSelector);
            if (oo.hasClass("open")) {
                oo.removeClass("open").addClass("close");
                $(listSelector).hide();
            } else if (oo.hasClass("close")) {
                oo.removeClass("close").addClass("open");
                $(listSelector).show();
            }

        },
        focus: function(obj) {
            var oo = $(obj);
            if (typeof oo.get(0) != "undefined") oo.get(0).focus();
        },
        openWindow: function(obj) {
            window.open(obj.href);
            return false;
        },
        closeWindow: function() {
            if ($.browser.msie && $.browser.version >= 7) {
                window.open("about:blank", "_self").close();
            } else {
                window.opener = self;
                self.close();
            }
        },
        anchor: function(target, speed, callback) {
            if (arguments.length == 1) {
                speed = 1000;
                callback = function() {};
            } else if (arguments.length == 2) {
                if (typeof speed == "undefind") {
                    speed = 1000;
                    callback = function() {};
                } else if (typeof speed == "function") {
                    callback = speed;
                    speed = 1000;
                }
            }

            target = $(target);
            var targetOffset = target.offset().top;
            $('html,body').animate({
                scrollTop: targetOffset
            }, speed, callback);
        },
        urlParam: function(paramsName, url) {
            if (bugs.valid.empty(paramsName)) return null;
            if (typeof url == "undefined") url = document.location.href;

            var idx = url.indexOf("?");
            if (idx > 0) {
                var queryString = url.substring(idx + 1);
                if (!bugs.valid.empty(queryString)) {
                    var params = queryString.split("&");
                    if (typeof params != "undefined" && params.length > 0) {
                        for (var i = 0; i < params.length; i++) {
                            var pStr = params[i].split("=");
                            var pName = pStr[0];
                            var pValue = pStr[1];
                            if (paramsName == pName) return pValue;
                        }
                    }
                }
            }
            return null;
        },
        trListUp: function(c) {
            var list = $(c).closest("table").find("tbody > tr");
            var tr = $(c).closest("tr");
            var idx = list.index(tr);
            if (idx <= 0) return;

            var before = list.eq(idx - 1);
            before.before(tr);
        },

        trListDown: function(c) {
            var list = $(c).closest("table").find("tbody > tr");
            var tr = $(c).closest("tr");
            var idx = list.index(tr);
            if (idx >= list.length - 1) return;

            var after = list.eq(idx + 1);
            after.after(tr);
        }
    },
    valid: {
        isNull: function(obj) {
            return (obj == null || obj == "" || obj == "<undefined>" || obj == "undefined" || obj == "NaN") ? true : false;
        },
        empty: function(str) {
            if (typeof str == "string" && bugs.utils.trim(str).length > 0) return false;
            return true;
        },
        email: function(str) {
            return (/\w+([-+.]\w+)*@\w+([-.]\w+)*\.[a-zA-Z]{2,4}$/).test(str);
        },
        kor: function(str) {
            str = bugs.utils.trim(str);
            return (/^[가-힝]+$/).test(str);
        },
        eng: function(str) {
            str = bugs.utils.trim(str);
            return (/^[a-zA-Z]+$/).test(str);
        },
        numeng: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9a-zA-Z]+$/).test(str);
        },
        notnumeng: function(str) {
            str = bugs.utils.trim(str);
            return (/[^0-9a-zA-Z]+$/).test(str);
        },
        numengkor: function(str) {
            str = bugs.utils.trim(str);
            return (/^[가-힝0-9a-zA-Z]+$/).test(str);
        },
        notkor: function(str) {
            str = bugs.utils.trim(str);
            return (/[가-힝]+/).test(str);
        },
        numdash: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9]{1}[0-9\-]+$/).test(str);
        },
        url: function(str) {
            str = bugs.utils.trim(str);
            return (/^http:\/\/([\w\-]+\.)+/).test(str);
        },
        num: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9]+$/).test(str);
        },
        special: function(str) {
            str = bugs.utils.trim(str);
            return (/^[\!,\@,\#,\$,\%,\^,\&,\*,\?,\_,\~]+$/).test(str);
        },
        numengspecial: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9a-zA-Z\!,\@,\#,\$,\%,\^,\&,\*,\?,\_,\~]+$/).test(str);
        },
        phone: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9]{1,3}-[0-9]{3,4}-[0-9]{4}$/).test(str);
        },
        dateYMD: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/).test(str);
        },
        dateYMDHS: function(str) {
            str = bugs.utils.trim(str);
            return (/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$/).test(str);
        },
        include2byte: function(str) {
            if (!str || typeof str != 'string') return false;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) > 127) return true;
            }
            return false;
        },
        isSsnCheck: function(strSsn) {
            strSsn = bugs.utils.trim(strSsn);
            if (strSsn.length != 13) return false;
            var isForeigner = false;
            switch (strSsn.substr(6, 1)) {
                case '5':
                case '6':
                case '7':
                case '8':
                    isForeigner = true;
                    break;
                default:
                    isForeigner = false;
                    break;
            }

            if (isForeigner) {
                return bugs.valid.isFgnSsnCheck(strSsn);
            } else {
                var strCheckKey = '234567892345';
                var nCheckNo = 0,
                    nCheckVal = 0,
                    rVal;

                for (var i = 0; i < strCheckKey.length; i++) {
                    nCheckNo += strSsn.charAt(i) * strCheckKey.charAt(i);
                }
                nCheckVal = strSsn.charAt(i);

                rVal = 11 - (nCheckNo % 11)
                if (rVal > 9) rVal = (rVal % 10);

                return (nCheckVal == rVal) ? true : false;
            }
        },
        isFgnSsnCheck: function(strSsn) {
            strSsn = bugs.utils.trim(strSsn);
            if (strSsn.length != 13) return false;
            var strCheckKey = '234567892345';
            var nCheckNo = 0,
                nCheckVal = 0,
                rVal;
            var nList = new Array(13);

            for (var i = 0; i < 13; i++) {
                nList[i] = strSsn.charAt(i);
            }

            if (nList[11] < 6) return false;
            if ((nList[7] * 10 + nList[8]) & 1) return false;

            for (var i = 0; i < strCheckKey.length; i++) {
                nCheckVal += nList[i] * strCheckKey.charAt(i);
            }

            if ((nCheckVal = 11 - (nCheckVal % 11)) >= 10) nCheckVal -= 10;
            if ((nCheckVal += 2) >= 10) nCheckVal -= 10;

            return (nCheckVal != nList[12]) ? false : true;
        }
    },
    mainurl: function() {
        var url = document.location.href;
        //return url;
        if (url.indexOf("www.bugs.co.kr") > 0) {
            return "http://www.bugs.co.kr";
        } else return _staticUrl;
    },
    url: {
        artistPage: function(artist_id) {
            if (typeof artist_id == "undefined") return;
            return g_urlMusic + "/artist/" + artist_id;
        },
        albumPage: function(album_id) {
            if (typeof album_id == "undefined") return;
            return g_urlMusic + "/album/" + album_id;
        },
        esAlbumPage: function(es_album_id) {
            if (typeof es_album_id == "undefined") return;
            return g_urlMusic + "/musicpd/albumview/" + es_album_id;
        },
        openAlbumPage: function(open_album_id) {
            if (typeof open_album_id == "undefined") return;
            return g_urlMusic + "/musicpd/openalbum/" + open_album_id;
        },
        trackPage: function(track_id) {
            if (typeof track_id == "undefined") return;
            return g_urlMusic + "/track/" + track_id;
        },
        memberPage: function(userId) {
            if (typeof userId == "undefined") return;
            return g_urlMe + "/" + userId;
        },
        albumThumbnail: function(album_id, size, ext) {
            if (typeof album_id == "undefined") return;
            if (typeof ext == "undefined") ext = ".jpg";
            return g_urlClipimg + "/album/images/" + size + "/" + Math.floor(album_id / 100) + "/" + album_id + ext;
        },
        mvThumbnail: function(mv_id, size) {
            if (typeof mv_id == "undefined") return;
            return g_urlClipimg + "/mv/images/" + size + "/" + Math.floor(mv_id / 100) + "/" + mv_id + ".jpg";
        },
        artistThumbnail: function(artist_id, size, ext) {
            if (typeof artist_id == "undefined") return;
            if (typeof ext == "undefined") ext = ".jpg";
            return g_urlClipimg + "/artist/images/" + size + "/" + Math.floor(artist_id / 100) + "/" + artist_id + ext;
        },
        defaultThumbnail: function(src, defaultSize) {
            var index = src.indexOf("?");
            src = decodeURIComponent(src.substring(index + 5));

            var tmp = src.split("/");
            var type = tmp[tmp.length - 7];
            var width, height;

            if (type == "member" || type == "playlist") {
                if (type == "member") type = "user";
                else type = "albumUser";
                width = height = defaultSize ? defaultSize : tmp[tmp.length - 5];
            } else {
                type = tmp[tmp.length - 5];
                if (type == "poll") type = "artist";
                else if (type == "essential") type = "album";

                width = defaultSize ? defaultSize : tmp[tmp.length - 3];
                height = width;
                if (type == "mv" && width == "80") height = "60";
                if (type == "mv" && width == "100") height = "75";
                if (type == "mv" && width == "135") height = "101";
                if (type == "mv" && width == "210") height = "158";
            }

            return "http://file.bugsm.co.kr/nbugs/common/i_" + type + width + "x" + height + ".gif";
        }
    }
}

bugs.template = bugs.create();
bugs.template.prototype = {
    initialize: function(tmpl, json) {
        this.setTemplate(tmpl);
        this.setData(json);
    },
    setFile: function(src) {
        // TODO
    },
    setTemplate: function(tmpl) {
        if (tmpl) this._template = tmpl;
    },

    setData: function(data) {
        if (data && data != "") {
            this._data = bugs.overed(this._data || {}, data || {});
        } else {
            this._data = {};
        }
    },
    html: function() {
        var js = this._template.replace(/[\r\t\n]/g, " ")
            .replace(/'(?=[^%]*%>)/g, "\t")
            .split("'").join("\\'")
            .split("\t").join("'")
            .replace(/<%=(.+?)%>/g, "',$1,'")
            .split("<%").join("');")
            .split("%>").join("write.push('");
        var f = new Function('obj', "var write=[];with (obj){write.push('" + js + "');}return write.join('');");
        if (!this._data) return f;
        var r = f(this._data);
        return r;
    }

}

bugs.layermenu = {
    TEMP_MV: '<div id="mvLayerMenu" class="layerMenu layerMenuMV <% if(obj.mvAdultYn == "Y") {%>layerAdultMsg<% } %>">' + '<% if(obj.mvAdultYn == "Y") {%><div class="adultMsg">청소년 유해 매체물입니다.</div><% } %>' + '<ul>' + '	<% if(obj.mediaYn == "Y") {%><li><a href="javascript:bugs.music.viewMV(<%=id%>,\'<%=obj.mvAdultYn%>\');">보기<span class=\"icon\"><%if(obj.mvGrade == "ALL") {%><span class=\"trackIcon icRatingAll\" title=\"전체관람가\"><span>전체관람가</span></span><%} else if(obj.mvGrade == "OVER_12") {%><span class=\"trackIcon icRating12\" title=\"12세관람가\"><span>12세관람가</span></span><%} else if(obj.mvGrade == "OVER_15") {%><span class=\"trackIcon icRating15\" title=\"15세관람가\"><span>15세관람가</span></span><%} else if(obj.mvGrade == "ADULT") {%><span class=\"trackIcon icRating19\" title=\"청소년관람불가\"><span>청소년관람불가</span></span><%}%></span></a></li><% } %>' + '	<% if(obj.svcFullhdYn == "Y") {%><li><a href="javascript:bugs.music.dnFullMV(<%=id%>,\'<%=obj.mvAdultYn%>\');">FULL HD 다운</a></li><% } %>' + '	<% if(obj.svcHdYn == "Y") {%><li><a href="javascript:bugs.music.dnHdMV(<%=id%>,\'<%=obj.mvAdultYn%>\');">HD 다운</a></li><% } %>' + '	<% if(obj.svcSdYn == "Y") {%><li><a href="javascript:bugs.music.dnSdMV(<%=id%>,\'<%=obj.mvAdultYn%>\');">일반화질 다운</a></li><% } %>' + '</ul>' + '<div class="layerBg bgTR"></div>' + '<div class="layerBg bgTL"></div>' + '<div class="layerBg bgTC"></div>' + '</div>',
    TEMP_PHONE: '<div id="phoneLayerMenu" class="layerMenu layerMenuPhone">' + '<ul>' + '	<% if(obj.livebellYn == "Y"){ %><li><a href="javascript:void(0);" onclick="bugs.music.setLivebell(<%=id%>);">라이브벨</a></li><% } %>' + '	<% if(obj.ringYn == "Y"){ %><li><a href="javascript:void(0);" onclick="bugs.music.setColoring(<%=id%>);">컬러링</a></li><% } %>' + '</ul>' + '<div class="layerBg bgTR"></div>' + '<div class="layerBg bgTL"></div>' + '<div class="layerBg bgTC"></div>' + '</div>',
    TEMP_PHONE_SET: '<div id="phoneSetLayerMenu" class="layerMenu layerMenuPhoneSetting" style="right:17px;top:40px;">' + '<ul>' + '	<li><a href="javascript:void(0);">설정</a></li>' + '	<li><a href="javascript:void(0);">선물</a></li>' + '</ul>' + '<div class="layerBg bgTR"></div>' + '<div class="layerBg bgTL"></div>' + '<div class="layerBg bgTC"></div>' + '</div>',
    mv: function(obj, mv_id, mediaYn, svcFullhdYn, svcHdYn, svcSdYn, mediaNo, mvAdultYn, mvGrade) {
        if (typeof mediaNo == "undefined") mediaNo = 0;
        if (typeof mvAdultYn == "undefined") mvAdultYn = 'N';
        if (typeof mvGrade == "undefined") mvGrade = '';

        if ($("#mvLayerMenu").length > 0) {
            $(document).unbind("click", bugs.layermenu.mvHideWhenDocumentClick);
            $("#mvLayerMenu").hide().remove();
        }

        var _tmp = new bugs.template(bugs.layermenu.TEMP_MV, {
            id: mv_id,
            mediaYn: mediaYn,
            svcFullhdYn: svcFullhdYn,
            svcHdYn: svcHdYn,
            svcSdYn: svcSdYn,
            mediaNo: mediaNo,
            mvAdultYn: mvAdultYn,
            mvGrade: mvGrade
        });
        var oobj = $(obj);
        var span = $(obj).parent();

        var layer = $(_tmp.html()).appendTo("body");;
        bugs.layermenu.layerEventHandler(oobj, layer, 3, 0);
        $(document).bind("click", {
            button: span,
            layer: layer
        }, bugs.layermenu.mvHideWhenDocumentClick);
    },
    mvHideWhenDocumentClick: function(e) {
        if (e.data.button.index(e.target) < 0 && e.data.button.children().index(e.target) < 0 && e.data.layer.index(e.target) < 0 && e.data.layer.children().index(e.target) < 0) {
            e.data.layer.hide().remove();
            $(document).unbind("click", bugs.layermenu.mvHideWhenDocumentClick);
        }
    },
    phone: function(obj, trackId, livebellYn, ringYn, _top, _left) {
        if (typeof _top == "undefined") _top = 3;
        if (typeof _left == "undefined") _left = 0;
        if ($("#phoneLayerMenu").length > 0) {
            $(document).unbind("click", bugs.layermenu.phoneHideWhenDocumentClick);
            $("#phoneLayerMenu").hide().remove();
            bugs.layermenu.phone(obj, trackId, livebellYn, ringYn, _top, _left);
            return;
        }

        var _tmp = new bugs.template(bugs.layermenu.TEMP_PHONE, {
            id: trackId,
            "ringYn": ringYn,
            "livebellYn": livebellYn
        });
        var oobj = $(obj);
        var span = $(obj).parent();

        var layer = $(_tmp.html()).appendTo("body");;
        bugs.layermenu.layerEventHandler(oobj, layer, _top, _left);
        $(document).bind("click", {
            button: span,
            layer: layer
        }, bugs.layermenu.phoneHideWhenDocumentClick);
    },
    phoneHideWhenDocumentClick: function(e) {
        if (e.data.button.index(e.target) < 0 && e.data.button.children().index(e.target) < 0 && e.data.layer.index(e.target) < 0 && e.data.layer.children().index(e.target) < 0) {
            e.data.layer.hide().remove();

            if (typeof bugs.home != "undefined") {
                if ((typeof bugs.home.chartTop10 != 'undefined') && bugs.home.chartTop10.isPhoneShow) {
                    bugs.home.chartTop10.isPhoneShow = false;
                    $("#content .top10 ul.top10List li").eq(bugs.home.chartTop10.phoneListNo).trigger("mouseout");
                }
            }
            $(document).unbind("click", bugs.layermenu.phoneHideWhenDocumentClick);
        }
    },
    phoneSet: function(obj, trackId, type) {
        if ($("#phoneSetLayerMenu").length > 0) {
            $(document).unbind("click", bugs.layermenu.phoneSetHideWhenDocumentClick);
            $("#phoneSetLayerMenu").hide().remove();
        }

        var _tmp = new bugs.template(bugs.layermenu.TEMP_PHONE_SET, {
            id: trackId
        });
        var oobj = $(obj);
        var span = $(obj).parent();
        /*
		<ul>'+
		'	<li><a href="javascript:void(0);">설정</a></li>'+
		'	<li><a href="javascript:void(0);">선물</a></li>'+
		'</ul>'+
		*/


        var layer = $(_tmp.html());
        layer.find("ul li a").each(function(idx) {
            if (type == "livebell") {
                if (idx == 0) $(this).click(function() {
                    bugs.music.setLivebell(trackId);
                });
                else if (idx == 1) $(this).click(function() {
                    bugs.music.setLivebellTo(trackId);
                });
            } else if (type == "coloring") {
                if (idx == 0) $(this).click(function() {
                    bugs.music.setColoring(trackId);
                });
                else if (idx == 1) $(this).click(function() {
                    bugs.music.setColoringTo(trackId);
                });
            }
        });

        layer.appendTo("body");
        bugs.layermenu.layerEventHandler(oobj, layer, 3, 0);
        $(document).bind("click", {
            button: span,
            layer: layer
        }, bugs.layermenu.phoneHideWhenDocumentClick);
    },
    phoneSetHideWhenDocumentClick: function(e) {
        if (e.data.button.index(e.target) < 0 && e.data.button.children().index(e.target) < 0 && e.data.layer.index(e.target) < 0 && e.data.layer.children().index(e.target) < 0) {
            e.data.layer.hide().remove();

            $(document).unbind("click", bugs.layermenu.phoneSetHideWhenDocumentClick);
        }
    },
    layerEventHandler: function(caller, layer, _top, _left) {
        var span = caller.parent();
        layer.css({
            "top": caller.offset().top + span.height() + _top,
            "left": caller.offset().left - (layer.width() / 2) + (caller.width() / 2) + _left
        }).show();

        $(window).resize(function() {
            layer.css({
                "top": caller.offset().top + span.height() + _top,
                "left": caller.offset().left - (layer.width() / 2) + (caller.width() / 2) + _left
            });
        });

    },
    layerEventHandler2: function(caller, layer, _top, _left) {
        //------------------ 브라우져별 예외 처리 -----------------//
        var yy = 0;
        var xx = 0;
        if ($.browser.name == "msie") {
            yy = -44;
            if ($.browser.versionNumber == "6") yy = -14;
        } else if ($.browser.name == "firefox") {
            yy = -10
        }
        if (caller.find("img").width() < 30) { // 뮤직라이프 작은 스타
            xx = xx - caller.find("img").width() - 3;
            if ($.browser.name == "msie") yy = yy + 10;
        } else if (caller.find("img").height() == 57) { // TOP 아티스트
            if ($.browser.name == "msie") yy = yy - 20;
        } else if (caller.find("img").width() == 83) { // TOP 아티스트  TOP3
            if ($.browser.name == "msie") yy = yy + 20;
        } else if (caller.find("img").width() == 35 && caller.find("img").height() == 35) { // 타인의 뮤직라이프 사람좋아
            xx = xx - 17;
        }

        if (caller.attr("type") == "image") { // 구매보관함/뮤비 > 좋아
            xx = xx - 10;
            yy = yy + 20;
            if ($.browser.name == "msie") yy = yy + 25;
        }
        //------------------ 브라우져별 예외 처리 -----------------//

        var e = caller.offset();
        var x = e.left + _left + xx;
        var y = e.top + caller.find("img").height() + _top + yy + 10;


        layer.css("left", x + "px");
        layer.css("top", y + "px");
        layer.show();
    },
    tracksClose: function() {},
    tracksSuccess: function(html, id, type, obj, left, top) {
        html = html.replace(/^\s*/, '');
        if (html != "") {
            var _layer = $("<div id=\"" + type + id + "\" class=\"layerPopup noTitle layerListenAll\" style='display:none;position:absolute;'></div>").appendTo($("body")).css("z-index", "1000");
            bugs.layermenu.trackLayerPosition(_layer, obj, left, top);
            _layer.html(html).show('blind');
            $(window).resize(function() {
                bugs.layermenu.trackLayerPosition(_layer, obj, left, top);
            });
        }
    },
    trackLayerPosition: function(layer, caller, left, top) {
        var e = caller.offset();
        var x = e.left + left;
        var y = e.top + caller.height() + top;
        layer.css({
            top: y,
            left: x
        });
    },
    tracks: function(id, type, obj, msrl) {
        if (false) {
            $("#" + type + id).remove();
        }
        $(".layerPopup.layerListenAll").hide();

        if (typeof obj == "undefined") {
            obj = $("#_" + type + id);
        } else obj = $(obj);

        var url, left, top, data;
        if (type == "PLAYLIST") {
            url = g_urlAjax + "/user/ajax/playlist/other/track";
            left = -32;
            top = 0;
            data = {
                "playlist_id": id,
                "msrl": msrl,
                "decorator": "blank"
            };
        } else if (type == "ALBUM") {
            url = g_urlAjax + "/user/ajax/album/other/track/" + id;
            left = -1;
            top = 0;
            data = {
                "decorator": "blank"
            };
        } else if (type == "ESALBUM") {
            url = g_urlAjax + "/openalbum/esential/ajax/track";
            left = -1;
            top = 0;
            data = {
                "id": id,
                "decorator": "blank"
            };
        } else {
            url = g_urlMe + "/ajax/album/other/track/" + id;
            left = -30;
            top = 0;
            data = {};
        }


        if ($("#" + type + id).html() == null) {
            $.get(url, data, function(html) {
                bugs.layermenu.tracksSuccess(html, id, type, obj, left, top);
            });
        } else {
            var e = obj.offset();
            var x = e.left + left;
            var y = e.top + obj.height() + top;
            $("#" + type + id).css({
                "top": y,
                "left": x
            }).show('blind');
        }
    },
    esTracks: function(id, obj) {
        bugs.layermenu.tracks(id, "ESALBUM", obj);
    },
    openalbumTracks: function(id, obj) {
        bugs.layermenu.tracks(id, "PLAYLIST", obj);
    },
    showClickLayer: function(sel) {
        $(sel).toggle();
        $(sel).find('.content').css('width', $(sel).width() - 5);
        $(sel).find('.bgTR').css('height', $(sel).find('.content').outerHeight());
    },

    descLayerDisplayNotAgain: function(sel) {
        var oDate = new Date();
        oDate.setDate(oDate.getDate() + 30);
        bugs.cookie.set(sel, "Y", oDate);
        $("#" + sel).hide();
    },

    descLayerDisplayCheck: function(sel) {
        if (bugs.cookie.get(sel) == "Y") {
            $("#" + sel).hide();
        } else {
            $("#" + sel).show();
            this.descLayerDisplaySizeCheck(sel);
        }
    },

    descLayerDisplaySizeCheck: function(sel) {
        $("#" + sel).find('.content').css('width', $("#" + sel).width() - 5);
        $("#" + sel).find('.bgTR').css('height', $("#" + sel).find('.content').outerHeight());
    }
};



bugs.form = {};
bugs.form.checkbox = bugs.create();
bugs.form.checkbox.prototype = {
    initialize: function(selector, name, value, option) {
        if (typeof selector != "string") this.checkbox = selector;
        else this.checkbox = $(selector);
        var _inp = this.checkbox.find("input");

        if (_inp.length > 0 && this.checkbox.find("input").get(0).disabled == true) {
            this._disabled = true;
            return;
        }

        this.name = name;
        if (arguments.length == 3 && typeof(value) != "string") {
            option = value;
        } else {
            if (typeof value == "string") this.value = value;
            this.value = value;
        }

        this.option = bugs.overed({
            checkedClass: "click",
            onchange: function() {},
            onclick: function() {},
            checked: function() {},
            unchecked: function() {}
        }, option || {});

        var _span = this.checkbox.find("span.checkbox:last");
        if (_span.length < 1) {
            this.checkbox.children().remove();
            _span = $("<span class=\"checkbox\"></span>").appendTo(this.checkbox);
        }
        this.clickObject = _span;
        var _inp = this.checkbox.find("span.checkbox:last input:checkbox:last");
        if (_inp.length < 1) {
            _inp = $('<input type="checkbox"/>').attr("name", this.name).attr("value", this.value).appendTo(_span);
        } else {
            if (bugs.valid.empty(_inp.attr("name"))) _inp.attr("name", this.name)
            /*
			if(!bugs.valid.empty(_inp.attr("value"))) {
				this.value = _inp.attr("value");
			}
			else*/
            _inp.attr("value", this.value);
        }

        this.hiddenObject = _inp;
        if (this.hiddenObject.get(0).checked == true) {
            this.checked();
        }

        this.checkbox.unbind("click", this._clickFunc);
        this.checkbox.click($.proxy(this._clickFunc, this));
    },
    _clickFunc: function(event) {
        //event.formObject = _formObject;
        var _input = this.hiddenObject.get(0);
        this.option.onclick(event);
        if (this.isChecked()) {
            this.unchecked();
        } else {
            this.checked();
        }
    },
    isDisabled: function() {
        if (this._disabled != "undefined" && this._disabled == true) return true;
        else return false;
    },
    isChecked: function() {
        return this.hiddenObject.get(0).checked;
    },
    checked: function() {
        this.checkbox.addClass(this.option.checkedClass);
        this.option.checked();
        this.hiddenObject.get(0).checked = true;
    },
    unchecked: function() {
        this.checkbox.removeClass(this.option.checkedClass);
        this.option.unchecked();
        this.hiddenObject.get(0).checked = false;


    },
    disabled: function() {},
    val: function(val) {
        if (typeof val != "string") return this.hiddenObject.attr("value");
        else this.hiddenObject.attr("value", val);
    },
    onchange: function(f) {
        var old = this.option.onchange;
        this.option.onchange = function(o, n) {
            old(o, n);
            f(o, n);
        }.bind(this);
    },
    onclick: function(f) {
        var old = this.option.onclick;
        this.option.onclick = function(o, n) {
            old(o, n);
            f(o, n);
        }.bind(this);
    },
    hide: function(speed) {
        if (speed) this.checkbox.hide(speed);
        else this.checkbox.hide();
    },
    show: function(speed) {
        if (speed) this.checkbox.show(speed);
        else this.checkbox.show();
    }
}

bugs.logging = {
    clientYN: false, //true => bugsplayer4
    url: g_urlAjax + "/logging/add",
    add: function(id, cols, nums, scriptYn) {
        if (typeof scriptYn == "undefined") scriptYn = false;
        if (this.clientYN) scriptYn = true;

        if (typeof id == "undefined" || id == null) return; //jhjung WAS null exception 추가 12.01.05
        if (typeof cols == "undefined" || cols == null) cols = [];
        if (typeof nums == "undefined" || nums == null) nums = [];
        if (cols.length == 0 && nums.length == 0) return;
        if (this.clientYN) cols.push("", "bugsplayer4");

        try {
            if (scriptYn) {
                jQuery.ajax({
                    url: g_urlWww + "/logging/add",
                    dataType: "script",
                    data: {
                        id: id,
                        "cols[]": cols,
                        "nums[]": nums
                    },
                    success: function(result) {}
                });

            } else {
                var _cols = [];
                $(cols).each(function() {
                    _cols.push(encodeURIComponent(this));
                });
                jQuery.post(bugs.logging.url, {
                    id: id,
                    "cols[]": _cols,
                    "nums[]": nums
                }, function(result) {

                });
            }
        } catch (ex) {
            bugs.log.log(ex);
        }


    }
}


bugs.gnb = {
    moreMenu: function() {
        var layerMore = $('.layerMore');
        if (layerMore.get(0).style.display == "none") {
            layerMore.show();

            var _close = function(event) {
                if ($('#tmMore, .layerMore, .layerMore *').index(event.target) < 0) {
                    layerMore.hide();
                    $(document).unbind("click", _close);
                }
            };
            $(document).bind("click", _close);
        } else {
            layerMore.hide();
        }
    },
    openMoreMenu: function() {
        $('.layerMore').show();
    },
    closeMoreMenu: function() {
        $('.layerMore').hide();
    },
    initSearch: function() {
        var _search = $("#gnbSearch");
        if (_search.length > 0) {
            _search.find("button").click(function() {});
        }
    },
    funcMemberBox: function(event) {
        if ($(".layerMyInfo, .layerMyInfo *, .viewMyInfo").index(event.target) < 0) {
            bugs.gnb.closeMemberBox();
            $(document).unbind("click", bugs.gnb.funcMemberBox);
        }
    },
    openMemberBox: function() {
        $('.layerMyInfo').slideDown(300);
        $(document).click(bugs.gnb.funcMemberBox);
    },
    closeMemberBox: function() {
        $('.layerMyInfo').slideUp(300);
    },
    toggleMemberBox: function() {
        if (bugs.visible($('.layerMyInfo'))) {
            bugs.gnb.closeMemberBox();
        } else {
            bugs.gnb.openMemberBox();
        }
        //javascript:void($('.layerMyInfo').show())
    },
    _topSearchHeight: function(ol) {
        var _h = 0;
        $("li", ol).each(function() {
            _h += $(this).height();
        });
        return _h;
    },
    topSearchRolling: function() {

        var rankList = $("#rankList");
        var isMouseOver = false;
        var dd = $("dd", rankList);
        var ol = dd.find("ol");

        if (rankList.length == 0 || dd.length == 0 || ol.length == 0) return;

        var _timeoutId;
        var rollingHeight = 40;
        //ol.height(bugs.gnb._topSearchHeight(ol));
        var _rollingFunc = function() {
            var _t, _h;
            if (ol.css("top") == "auto") _t = 0;
            else _t = bugs.math.abs(ol.position().top);

            if (ol.css("height") == "auto") _h = 0;
            else _h = bugs.gnb._topSearchHeight(ol);

            if (_t >= _h) {
                ol.css("top", rollingHeight);
                ol.animate({
                    top: "-=" + rollingHeight
                }, 1000, _rollingFunc);
            } else {
                _timeoutId = setTimeout(function() {
                    ol.animate({
                        top: "-=" + rollingHeight
                    }, 1000, _rollingFunc);
                }, 3000);
            }

        };

        rankList.hover(

        function(event) {
            dd.find("ol:animated").stop();
            ol.css("top", 0);
            if (typeof _timeoutId != "undefined" && _timeoutId != null) {
                clearTimeout(_timeoutId);
                _timeoutId = null;
            }
            rankList.removeClass("rankList").addClass("layerRank");
            $('.rankup').css({
                'z-index': '10'
            });
        }, function(event) {
            rankList.removeClass("layerRank").addClass("rankList");
            $('.rankup').css({
                'z-index': '1'
            });
            _rollingFunc();
        });
        _rollingFunc();
    },
    topComingSoonRolling: function() {

        var comingsoon = $("#comingsoon");
        var isMouseOver = false;
        var dd = $("dd", comingsoon);
        var ul = dd.find("ul");

        if (comingsoon.length == 0 || dd.length == 0 || ul.length == 0) return;

        bugs.log.log(comingsoon);
        var _timeoutId;
        var rollingHeight = 16;
        ul.height(bugs.gnb._topSearchHeight(ul));

        var _rollingFunc = function() {
            var _t, _h;
            if (ul.css("top") == "auto") _t = 0;
            else _t = bugs.math.abs(ul.position().top);

            if (ul.css("height") == "auto") _h = 0;
            else _h = bugs.gnb._topSearchHeight(ul);

            if (_t >= _h) {
                ul.css("top", rollingHeight);
                ul.animate({
                    top: "-=" + rollingHeight
                }, 1000, _rollingFunc);
            } else {
                _timeoutId = setTimeout(function() {
                    ul.animate({
                        top: "-=" + rollingHeight
                    }, 1000, _rollingFunc);
                }, 3000);
            }

        };

        dd.hover(

        function(event) {
            dd.find("ul:animated").stop();
            if (typeof _timeoutId != "undefined" && _timeoutId != null) {
                clearTimeout(_timeoutId);
                _timeoutId = null;
            }
        }, function(event) {
            _rollingFunc();
        });
        _rollingFunc();
    },
    _topKeywordsHtml: '<% for(var i=0; i < obj.list.length; i++) { var item = obj.list[i]; %>' + '<li class="<%=item.info.rankClass%> <%= item.info.class2%>">' + '<span class="ranking"><%=item.info.rank%>.</span>' + '<span class="word"><a href="<%=g_urlSearch + \"/total?q=\" + encodeURIComponent(item.query)%>"><%=item.query%></a></span> ' + '<span class="updown"><em><%=item.info.rackName%></em> <% if(typeof item.deltaRanking != "undefined") { %><strong><%=item.info.rankStr%></strong><% } %></span></li>' + '<% } %>',
    _topKeywordsHtmlMain: '<% for(var i=0; i < obj.list.length; i++) { var item = obj.list[i]; %>' + '<li class="<%=item.info.rankClass%> <%= item.info.class2%>">' + '<span class="ranking"><%=item.info.rank%>.</span>' + '<span class="word"><a href="<%=g_urlSearch + \"/total?q=\" + encodeURIComponent(item.query)%>&wl_ref=gnb_search<% if(i<9){%>0<%}%><%=i+1%>"><%=item.query%></a></span> ' + '<span class="updown"><em><%=item.info.rackName%></em> <% if(typeof item.deltaRanking != "undefined") { %><strong><%=item.info.rankStr%></strong><% } %></span></li>' + '<% } %>',
    topKeywords: function() {
        $.ajax({
            url: g_urlAjax + "/search/top",
            success: function(result) {
                if (typeof result == "undefined" || $.isArray(result) == false || result.length == 0) return;
                $(result).each(function(idx) {
                    var _rank = {};
                    _rank.rank = idx + 1;
                    if (typeof this.deltaRanking == "undefined" || this.deltaRanking == null) {
                        _rank.rankClass = "new";
                        _rank.rankName = "NEW";
                        _rank.rankStr = "";
                    } else if (this.deltaRanking > 0) {
                        _rank.rankClass = "down";
                        _rank.rankName = "하락";
                        _rank.rankStr = this.deltaRanking;
                    } else if (this.deltaRanking == 0) {
                        _rank.rankClass = "same";
                        _rank.rankName = "동일";
                        _rank.rankStr = "-";
                    } else if (this.deltaRanking < 0) {
                        _rank.rankClass = "up";
                        _rank.rankName = "NEW";
                        _rank.rankStr = this.deltaRanking * (-1);
                    }

                    if (idx < 2) _rank.class2 = " top3";
                    else if (idx == 2) _rank.class2 = " top3 divider";
                    else _rank.class2 = "";

                    this.info = _rank;
                });
                if ($("#container").hasClass("main")) var _tmp = new bugs.template(bugs.gnb._topKeywordsHtmlMain, {
                    "list": result
                });
                else var _tmp = new bugs.template(bugs.gnb._topKeywordsHtml, {
                    "list": result
                });
                $("#rankList dd ol").html(_tmp.html());

                // top keywords scrolling
                //bugs.gnb.topSearchRolling();
            },
            dataType: "json"
        });
    },
    chkLoginCode: function() {
        var code = bugs.utils.urlParam("loginCode");
        var msrl = bugs.utils.urlParam("msrl");
        if (!bugs.valid.empty(code)) {
            bugs.ui.showLoginAlert(code, {
                msrl: "",
                msrl: ((typeof msrl == "undefined" || msrl == null) ? "" : msrl),
                layerLogin: false
            });
        }

    }
}


var debug = {
    dump: function() {
        var retVal = '',
            argVal = arguments[0] || '';

        switch ((typeof argVal).toLowerCase()) {
            case 'object':
                $.each(argVal, function(key, value) {
                    retVal += '[' + (typeof value) + '] ' + key + ' => ' + value + '\n';
                });
                break;

            case 'string':
            default:
                retVal += (typeof argVal) + '/' + argVal;
        }
        return retVal;
    }
};

searchBoxAd = {
    enable: true,
    url: null,
    init: function(url) {
        if (typeof url == "undefined") {
            searchBoxAd.url = $("#_searchBoxAdUrl").val();
        } else {
            searchBoxAd.url = url;
        }
        $(".commonHeader .search .searchField .btnClearAd").bind("click", searchBoxAd.close).focus(function() {
            this.blur();
        });
        $("#searchInput").bind("focus", searchBoxAd.close);
        $(".commonHeader .search .searchField button[type=button]").click(searchBoxAd.clickButton);
    },
    close: function(event) {
        var clearAnchor = $(".searchField .btnClearAd");
        var input = $("#searchInput");
        event.preventDefault();
        clearAnchor.hide().remove();
        input.val("")
            .unbind("focus", searchBoxAd.close)
            .removeClass("adKeyword")
            .focus();
        searchBoxAd.enalbe = false;
        $(".commonHeader .searchField button[type=button]").unbind("click", searchBoxAd.clickButton);
    },
    clickButton: function(event) {
        document.location.href = searchBoxAd.url;
        event.stopPropagation();
    }
};


$(document).ready(function() {
    if ($(document.body).length > 0) {
        var brName = $.browser.name;
        if (brName == "msie") {
            var verNumber = $.browser.versionNumber;
            if (verNumber == 5) {} else if (verNumber == 6) {
                $("body").addClass("ie6");
            } else if (verNumber == 7) {
                $("body").addClass("ie7");
            }
        } else if (brName == "firefox") {
            $("body").addClass("ff3_5");
        }
    }
});

var buyCash = function() {
    window.open(g_urlBilling + '/pay/pg/popProcess', 'cash', 'top=10, left=10, width=750, height=564, toolbar=0, directories=0, status=0, menubar=0, scrollbars=0, resizable=0');
};


if ("undefined" == typeof bugs.fb) {
    bugs.fb = {
        appid: "122936701116206",
        scope: ['email', 'read_stream', 'publish_actions'],
        loginPage: g_urlWww + "/facebook/paramgate2?gourl=" + location.href,
        twtUrl: "http://twtevent.co.kr",
        getMyByAccessToken: function(access_token) {
            var path = 'https://graph.facebook.com/me?access_token=' + access_token;

            var queryParams = ['access_token=' + access_token, 'redirect_uri=' + window.location];
            var query = queryParams.join('&');
            var url = path + query;
            location.href = url;
        },
        getHost: function() {
            if (location.href.indexOf(g_urlMusic) != -1) return g_urlMusic;
            else if (location.href.indexOf(g_urlSearch) != -1) return g_urlSearch;
            else if (location.href.indexOf(g_urlSecure) != -1) return g_urlSecure;
            else if (location.href.indexOf(bugs.fb.twtUrl) != -1) return bugs.fb.twtUrl;
            else
            // if (location.href.indexOf(g_urlWww ) != -1)
            if (g_urlWww == "undefined") return "http://www.bugs.co.kr";
            else return g_urlWww;
        },
        goFBConnect: function(access_token, data_agree) {
            var params = {
                "agree": data_agree,
                "access_token": access_token
            };
            $.post(this.getHost() + "/facebook/ajax/login", params, function(
            data) {
                if (data) {
                    // alert(data.result);
                    if (data.result == "OK" || data.result == "OK_NEW") {
                        if (typeof(g_msrl) == "undefined"); {
                            location.reload();
                        }
                    } else if (data.result == "NOT_AGREE") {
                        // 동의 페이지로 이동
                        location.href = g_urlWww + "/fb/agree?access_token=" + access_token;
                    }
                } else {
                    // 기타 오류 발생
                }
            }, "json");
        },
        loginFBAfterCheck: function(uid) {
            var params = {
                "uid": uid
            };
            $.post(g_urlAjax + "/facebook/checkconnect", params, function(data) {
                if (data) {
                    //alert(data.result);
                    if (data.result == "CONNECTED") {

                        //alert("data.access_token:"+data.access_token);
                        // go login
                        location.href = g_urlSecure + "/facebook/auth?access_token=" + data.access_token + "&song=" + encodeURIComponent(location.href);
                    } else {
                        //alert("오류 발생2");
                    }
                } else {
                    // 기타 오류 발생
                    //alert("오류  발생1");
                }
            }, "json");
        },
        doAuth: function() {

            FB.login(function() {
                if (typeof(fbResponse) != "undefined" && fbResponse.authResponse) {
                    var accessToken = fbResponse.authResponse.accessToken;
                    var uid = 0;
                    FB.api('/me', function(response) {
                        uid = response.id;
                        alert(uid);
                    });

                } else {
                    // 회원이 로그인 취소 했을 경우
                }
            }, {
                scope: 'email,user_activities,user_likes,user_birthday,offline_access,publish_stream,publish_actions'
            });

        },

        openLogin: function() {
            window.open(g_urlAjax + "/facebook/login?returl=" + location.href, "FBLOGIN", 'scrollbars=yes,resizable=yes,width=1000,height=570');
            /*	
			window.open(this.getHost() + "/facebook/login?returl="
					+ location.href, "FBLOGIN",
					"width=1000,height=570,resizable=yes;scrollbars=yes");
			*/
        },
        openLoginEvent: function() {

            var locationUrl = location.href.substring(0, location.href.indexOf("?") == -1 ? location.href.length : location.href.indexOf("?"));
            window.open(g_urlAjax + "/facebook/login?returl=" + locationUrl, "FBLOGIN", 'scrollbars=yes,resizable=yes,width=1000,height=570');
            /*	
			window.open(this.getHost() + "/facebook/login?returl="
					+ location.href, "FBLOGIN",
					"width=1000,height=570,resizable=yes;scrollbars=yes");
			*/
        },

        openForConnect: function() {
            window.open(this.getHost() + "/facebook/connect?returl=" + location.href, "FBLOGIN", "width=1000,height=570,resizable=0");

        }
    };
}


Date.prototype.format = function(format) {
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {
        var curChar = format.charAt(i);
        if (i - 1 >= 0 && format.charAt(i - 1) == "\\") {
            returnStr += curChar;
        } else if (replace[curChar]) {
            returnStr += replace[curChar].call(this);
        } else if (curChar != "\\") {
            returnStr += curChar;
        }
    }
    return returnStr;
};
Date.replaceChars = {
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    d: function() {
        return (this.getDate() < 10 ? '0' : '') + this.getDate();
    },
    D: function() {
        return Date.replaceChars.shortDays[this.getDay()];
    },
    j: function() {
        return this.getDate();
    },
    l: function() {
        return Date.replaceChars.longDays[this.getDay()];
    },
    N: function() {
        return this.getDay() + 1;
    },
    S: function() {
        return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th')));
    },
    w: function() {
        return this.getDay();
    },
    z: function() {
        var d = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((this - d) / 86400000);
    },
    W: function() {
        var d = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7);
    },
    F: function() {
        return Date.replaceChars.longMonths[this.getMonth()];
    },
    m: function() {
        return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1);
    },
    M: function() {
        return Date.replaceChars.shortMonths[this.getMonth()];
    },
    n: function() {
        return this.getMonth() + 1;
    },
    t: function() {
        var d = new Date();
        return new Date(d.getFullYear(), d.getMonth(), 0).getDate();
    },
    L: function() {
        var year = this.getFullYear();
        return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
    },
    o: function() {
        var d = new Date(this.valueOf());
        d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3);
        return d.getFullYear();
    },
    Y: function() {
        return this.getFullYear();
    },
    y: function() {
        return ('' + this.getFullYear()).substr(2);
    },
    a: function() {
        return this.getHours() < 12 ? 'am' : 'pm';
    },
    A: function() {
        return this.getHours() < 12 ? 'AM' : 'PM';
    },
    B: function() {
        return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24);
    },
    g: function() {
        return this.getHours() % 12 || 12;
    },
    G: function() {
        return this.getHours();
    },
    h: function() {
        return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12);
    },
    H: function() {
        return (this.getHours() < 10 ? '0' : '') + this.getHours();
    },
    i: function() {
        return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();
    },
    s: function() {
        return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds();
    },
    u: function() {
        var m = this.getMilliseconds();
        return (m < 10 ? '00' : (m < 100 ? '0' : '')) + m;
    },
    e: function() {
        return "Not Yet Supported";
    },
    I: function() {
        return "Not Yet Supported";
    },
    O: function() {
        return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00';
    },
    P: function() {
        return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00';
    },
    T: function() {
        var m = this.getMonth();
        this.setMonth(0);
        var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1');
        this.setMonth(m);
        return result;
    },
    Z: function() {
        return -this.getTimezoneOffset() * 60;
    },
    c: function() {
        return this.format("Y-m-d\\TH:i:sP");
    },
    r: function() {
        return this.toString();
    },
    U: function() {
        return this.getTime() / 1000;
    }
}; 